from Config.setting import collection
# from mitm_models import Data
# from typing import List


async def get_data(page: int, per_page: int):
    """
    获取数据
    """
    limit = per_page
    skip = (page - 1) * limit
    cursor = collection.find().sort("_id", -1).skip(skip).limit(limit).max_time_ms(3000)  # 设置查询的最大执行时间为3秒
    data = []
    async for document in cursor:
        document["_id"] = str(document["_id"])  # 将 ObjectId 转换为字符串
        data.append(document)
    total_count = await collection.count_documents({})
    return {"total": total_count, "page": page, "size": limit, "data": data}


async def get_total_documents() -> int:
    """
    获取总数
    """
    return await collection.count_documents({})


async def search_data(path: str, page: int, per_page: int):
    """
    搜索数据, 默认倒序查询
    """
    query = {"path": {"$regex": path, "$options": "i"}}
    cursor = collection.find(query).sort("_id", -1).max_time_ms(3000)  # 设置查询的最大执行时间为3秒
    results = []
    async for document in cursor:
        document["_id"] = str(document["_id"])  # 将 ObjectId 转换为字符串
        results.append(document)
    total_count = len(results)

    paginated_results = results[(page - 1) * per_page: page * per_page]

    return {"total": total_count, "page": page, "size": per_page, "data": paginated_results}
